﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Aribaccio.Security
{
    /// <summary>
    /// 不可逆 MD5加密解密算法
    /// </summary>
    [ComVisible(true)]
    [ComSourceInterfaces(typeof(ISecurity))]
    [ClassInterface(ClassInterfaceType.AutoDispatch)]
    public class SecurityMD5:  ISecurity
    {
        /// <summary>
        /// 加密方法
        /// </summary>
        /// <param name="argEncryptString">待加密的明文</param>
        /// <returns>加密密文字符串</returns>
        public string Encrypt(string argEncryptString)
        {
            //检查，密文不得为空
            if (string.IsNullOrEmpty(argEncryptString)) { return string.Empty; }
            //MD5 mClassMD5 = new MD5CryptoServiceProvider();
            MD5 mClassMD5 = MD5.Create();
            string mEncrypt = "";
            try
            {
                //将要加密的字符串转换为字节数组
                byte[] bytes = Encoding.Default.GetBytes(argEncryptString);
                //将字符串加密后也转换为字符数组
                byte[] cryptbytes = mClassMD5.ComputeHash(bytes);

                //加密方法1：转换成字符串，转换出来的字符串会在每个字符中间产生一个分隔符，需要去除掉
                mEncrypt = BitConverter.ToString(cryptbytes).Replace("-", "");
                
                //加密方法2：创建哈希字符串适用于任何 MD5 哈希函数 （在任何平台） 上创建 32 个字符的十六进制格式哈希字符串
                //StringBuilder strBuilder = new StringBuilder();
                //for (int i = 0; i < cryptbytes.Length; i++)
                //{
                //    strBuilder.Append(cryptbytes[i].ToString("x2"));
                //}
                //mEncrypt = strBuilder.ToString();

                //加密方法3：将加密后的字节数组转换为加密字符串
                //mEncrypt = Convert.ToBase64String(cryptbytes);

                //最后转换大写返回
                mEncrypt = mEncrypt.ToUpper();
            }
            catch (ArgumentException) { mEncrypt = string.Empty; }
            catch (CryptographicException) { mEncrypt = string.Empty; }
            catch (Exception) { mEncrypt = string.Empty; }
            finally { mClassMD5.Clear(); }
            return mEncrypt;
        }
        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="argDecryptString">待解密的密文</param>
        /// <returns>解密明文字符串</returns>
        public string Decrypt(string argDecryptString)
        {
            return argDecryptString;
        }
    }
}
